// subpkg_worker/medicine_record/medicine_record.js

import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    term:'',
    //解决刚开始频率错乱
    ret:0,
    total_medicineList:[],
    listId_long:'',
    listId_short:'',
    medicineList1:[],
    show: false,
    show1: false,
    elderId:'',
    show_pop:false,
    prescriptionName:'',
    chooseBgcolor:'red',
    chooseBgcolor2:'white',
    activeNames: ['1'],
    display1:'none',
    display2:'none',
    display_show1:'block',
    display_show2:'none',
    frequencyList: [],
    currentDate: '12:00',
    minHour: 0,
    maxHour: 24,
    //处理name
    value_0:0,
    //处理takeTime
    value_1: 0 ,
    //频次
    index:0,
    //哪个药物
    index1:0,
    index1_copy:0,
    valueList:
    [
      {
        value0:0,
        value1:0,
        value2:0,
        value3:0,
        value5:0
      }
    ],
    medicineList:
    [
      {
        frequencyId:'1',
        dosage:'',
        elderlyId:'',
        nurseId:'',
        startTime:'',
        endTime:'',
        medicationId:'1111111111111111111',
        takeTime:'',
        type:'口服',
        mode:'注射剂',
        unit:'mg'
      }
    ],
    option0:
    [

    ],
    option1: [
      { text: '注射剂', value: 0 },
      { text: '片剂', value: 1 },
      { text: '复方', value: 2 },
      { text: '丸剂', value: 3 },
      { text: '洗剂', value: 4 },
      { text: '合剂', value: 5 },
      { text: '酊剂', value: 6 },
      { text: '粉剂', value: 7 },
      { text: '胶囊剂', value: 8 },
      { text: '栓剂', value: 9 },
      { text: '糖浆剂', value: 10 },
      { text: '软膏剂', value: 11 }
    ],
    option2: [
      { text: 'mg', value: 0},
      { text: 'g', value: 1 },
      { text: 'μg', value: 2 },
      { text: 'ml', value: 3},
      { text: 'l', value: 4 },
      { text: 'μl', value: 5 },
      { text: '粒', value: 6},
      { text: '片', value: 7 },
      { text: '丸', value: 8 },
      { text: '袋', value: 9},
      { text: '滴', value: 10 }
    ],
    option3: [
      { text: '每日一次', value: 0},
      { text: '每日两次', value: 1 },
      { text: '每日三次', value: 2 },
      { text: '每日四次', value: 3},
      { text: '隔天一次', value: 4 },
      { text: '每早一次', value: 5 },
      { text: '每晚一次', value: 6},
      { text: '每小时一次', value: 7 },
      { text: '每两小时一次', value: 8 },
      { text: '每四小时一次', value: 9},
      { text: '每六小时一次', value: 10 },
      { text: '每八小时一次', value: 11 },
      { text: '临睡前', value: 12 },
    ],
    option5: [
      { text: '口服给药', value: 0},
      { text: '皮下给药', value: 1 },
      { text: '注射给药', value: 2 },
      { text: '肌内注射', value: 3},
      { text: '静脉滴注', value: 4}
    ],
   
    value0:0,
    value1:0,
    value2:0,
    value3:0,
    value5:0
    
  },

  //给药频次弹出层
  showPopup(e){
    var index = e.currentTarget.dataset.index
    this.setData({
      show_pop:true,
      index:index
    })
  },
  onClose_pop() {
    this.setData({ show_pop: false });
  },
  //选择入药时间
  onInput(event) {
    this.setData({
      currentDate: event.detail
    });
  },
  
  onconfirm_pop(e){
    console.log(e)
    var frequencyList = this.data.frequencyList
    var medicineList = this.data.medicineList
    frequencyList[this.data.index1][this.data.index] = `${e.detail}:00`
    medicineList[this.data.index1].takeTime = frequencyList[this.data.index1].join(';')

    // if(this.data.index === this.data.valueList[this.data.index1].value3){
    //   var takeTime = frequencyList[this.data.index1].join(';')
    //   medicineList[this.data.index1].takeTime = takeTime
    //   this.setData({
    //     medicineList:medicineList
    //   })
    // }
   
    this.setData({
      show_pop:false,
      frequencyList:frequencyList,
      medicineList:medicineList
    })
  },
  oncancel_pop(){
    this.setData({
      show_pop:false
    })
  },
  

  onDisplay() {
    console.log(1)
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    console.log(date)
    date = new Date(date);
    if(date.getMonth()+1 < 10 ){
      if(date.getDate() < 10){
        return `${date.getFullYear()}-0${date.getMonth() + 1}-0${date.getDate()} 00:00:00`;
      }
      return `${date.getFullYear()}-0${date.getMonth() + 1}-${date.getDate()} 00:00:00`;
    }
    else{
      if(date.getDate() < 10){
        return `${date.getFullYear()}-${date.getMonth() + 1}-0${date.getDate()}`;
      }
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    }
  },
  onConfirm(event) {
    var index1 = this.data.index1
    const medicineList = this.data.medicineList
    medicineList[index1].startTime = this.formatDate(event.detail)
    console.log(this.data.show1)
    this.setData({
      show: false,
      medicineList:medicineList
    });
  },

  onDisplay1() {
    this.setData({ show1: true });
  },
  onClose1() {
    this.setData({ show1: false });
  },
  onConfirm1(event) {
    var index1 = this.data.index1
    const medicineList = this.data.medicineList
    medicineList[index1].endTime = this.formatDate(event.detail)
    this.setData({
      show1: false,
      medicineList:medicineList
    });
  },
  
  changeShow1(){
    this.setData({
      display_show2:'none',
      display_show1:'block',
      chooseBgcolor:'red',
      chooseBgcolor2:'white'

    })
  },
  changeShow2(){
    this.setData({
      display_show1:'none',
      display_show2:'block',
      chooseBgcolor:'white',
      chooseBgcolor2:'red'
    })
  },

  
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
    //设置index1控制哪个药物
    var index1 = event.currentTarget.dataset.index
    this.setData({
      index1:index1
    })
  },

    
 

  bindName(e,index){
    var medicineList = this.data.medicineList
    var index1 = e.detail
    console.log(index1)

    const valueList = this.data.valueList
    valueList[index].value0 = e.detail
    this.setData({
      valueList:valueList,
      medicineList:medicineList
    })
    this.queryMsg(index)
  },
  bindType(e,index){
    var medicineList = this.data.medicineList
    var index1 = e.detail
    console.log(index1)
    medicineList[index].type = this.data.option1[index1].text
    const valueList = this.data.valueList
    valueList[index].value1 = e.detail
    this.setData({
      medicineList:medicineList,
      valueList:valueList
    })
  },
  bindUnit(e,index){
    var medicineList = this.data.medicineList
    var index1 = e.detail
    
    medicineList[index].unit = this.data.option2[index1].text
    const valueList = this.data.valueList
    valueList[index].value2 = e.detail
    this.setData({
      medicineList:medicineList,
      valueList:valueList
    })
  },
  bindfrequency(e,index){
    console.log(e)
    var medicineList = this.data.medicineList
    var index1 = e.detail
    medicineList[index].frequencyId = index1 + 1
    const valueList = this.data.valueList
    valueList[index].value3 = e.detail
    this.setData({
      value_1:index1,
      medicineList:medicineList,
      valueList:valueList
    })
  },
 
  bindway(e,index){
    console.log(index)
    var medicineList = this.data.medicineList
    var index1 = e.detail
    const valueList = this.data.valueList
    valueList[index].value5 = e.detail
    medicineList[index].mode = this.data.option5[index1].text
    this.setData({
      medicineList:medicineList,
      valueList:valueList
    })
  },
  bindCount(e,index){
    var medicineList = this.data.medicineList
    medicineList[index].dosage = e.detail.value
    this.setData({
      medicineList:medicineList
    })
  },



  changeType(e){
    console.log(e.currentTarget.dataset.index)
    this.bindType(e,e.currentTarget.dataset.index)
  },
  changeWay(e){
    console.log(e.currentTarget.dataset.index)
    this.bindway(e,e.currentTarget.dataset.index)
  },
  changeName(e){
    console.log(e.currentTarget.dataset.index)
    this.bindName(e,e.currentTarget.dataset.index)
  },
  changeCount(e){
    this.bindCount(e,e.currentTarget.dataset.index)
  },
  changeFrequency(e){
    // var index1 = e.currentTarget.dataset.index
    // this.setData({
    //   index1:index1
    // })
    // console.log(index1)
    var frequencyList = this.data.frequencyList
    var frequencyList1 = new Array(e.detail+1)
    if(frequencyList1.length===1){
      frequencyList1[0] = '12:00:00'
    }else if(frequencyList1.length===2){
      frequencyList1[0] = '12:00:00'
      frequencyList1[1] = '18:00:00'
    }
    else if(frequencyList1.length===3){
      frequencyList1[0] = '8:00:00'
      frequencyList1[1] = '12:00:00'
      frequencyList1[2] = '18:00:00'
    }
    if(this.data.index1===this.data.index1_copy&&frequencyList.length!=0){
      frequencyList.splice(this.data.index1,1)
    }
    if(this.data.index1!=this.data.index1_copy){
      this.setData({
        index1_copy:this.data.index1
      })
      if(this.data.index1<frequencyList.length){
        frequencyList.splice(this.data.index1,1)
      }
    }
    frequencyList.splice(this.data.index1,0,frequencyList1)
    this.setData({
      // value3:e.detail,
      frequencyList:frequencyList
    })
    this.bindfrequency(e,e.currentTarget.dataset.index)
  },
  changeUnit(e){
    this.bindUnit(e,e.currentTarget.dataset.index)
  },
  



  record(){
    var medicineList = this.data.medicineList
    var total_medicineList = this.data.total_medicineList
    for(var i =0;i<total_medicineList.length;i++){
      for(var j = 0 ; j <medicineList.length; j++){
        if(medicineList[j].medicationId === total_medicineList[i].medication.id){
          Toast(`"药物"${total_medicineList[i].medication.name}"已存在,该药物添加失败!`)
          return
        }
      }
    }
    var frequencyList = this.data.frequencyList
    for(var i in medicineList){
      medicineList[i].takeTime = frequencyList[i].join(';')
    }
    this.setData({
      medicineList:medicineList
    })
    for (var i in medicineList){
      if(medicineList[i].startTime===''||medicineList[i].endTime===''){
        Toast(`"药物${parseInt(i)+1}"的起止时间有误！`)
        return
      }
      var starttime = new Date(medicineList[i].startTime)
      var endtime = new Date(medicineList[i].endTime)
      if(endtime.getTime()-starttime.getTime()<0){
        Toast(`"药物${parseInt(i)+1}"的起止时间有误！`)
        return
      }
      
      var duration = (endtime.getTime()-starttime.getTime())/1000/60/60/24
      console.log(duration)
      if(duration<5&&this.data.term=='长期'){
        Toast(`"长期药物时长应至少大于5天，请重新选择`)
        return
      }
      if(duration>=5&&this.data.term=='短期'){
        Toast(`"短期药物时长不能超过5天，请重新选择，或者去长期药物中添加`)
        return
      }
      //长期药方
      if(this.data.term=='长期'){
        if(this.data.listId_long===''){
          this.create(medicineList[i])
        }else{
          this.add(medicineList[i],this.data.listId_long)
        }
      }
      //短期药方
      else{
        if(this.data.listId_short===''){
          this.create(medicineList[i])
        }else{
          this.add(medicineList[i],this.data.listId_short)
        }
      }

    }
  },
  create(medication){
    var medicineList = []
    medicineList.push(medication)
    wx.request({
      url: 'https://zhixiao.site:8080/client/medication_list/add',
      method:'POST',
      header: {  
        "Content-Type": "application/json"
      },
      data:{
        medicineList:medicineList
      },
      success:(res)=>{
        console.log("create")
        Toast('添加成功')
        console.log(res)
        
      },
      complete:(res)=>{
        this.queryMedicineList()
        this.createRecord()
      }
    })
  },
  add(medication,listNum){
    var medicineList = []
    medicineList.push(medication)
    wx.request({
      url: `https://zhixiao.site:8080/client/medication_list/add?listId=${listNum}`,
      method:'POST',
      header: {  
        "Content-Type": "application/json"
      },
      data:{
        medicineList:this.data.medicineList
      },
      success:(res)=>{
        console.log("add")
        Toast('添加成功')
        console.log(res)
      },
      complete:(res)=>{
        this.queryMedicineList()
        this.createRecord()
      }
    })
  },

  createRecord(){
    wx.request({
      url: 'https://zhixiao.site:8080/medication-record/generate',
      success:(res)=>{
      }
    })
  },

  
  query(){
    const that = this
    wx.request({
      url: 'https://zhixiao.site:8080/client/medicineName/query',
      success:(res)=>{
        var option= []
        for(var i = 0;i<res.data.data.length;i++){
            option.push({text:res.data.data[i],value:option.length})
        }
        this.setData({
          option0:option
        })
      },
      complete:(res)=>
      {
        that.queryMsg()
      }
    })
  },

  queryMsg(index){
    const that = this
    if(index===undefined){
      index = 0
    }
    wx.request({
      url: 'https://zhixiao.site:8080/client/medicine/query',
      data:{
        name:this.data.option0[this.data.valueList[index].value0].text
      },
      success:(res)=>{
        console.log(res.data.data)
        var recommendMsg = res.data.data
        const medicineList = this.data.medicineList
        
        medicineList[index].medicationId = recommendMsg.id
        this.setData({
          medicineList:medicineList
        })
        that.match(recommendMsg,index)
      }
    })
  },

  match(msg,index){
    console.log("匹配")
    console.log(msg)
    var lengthList = [this.data.option1.length,this.data.option2.length,this.data.option3.length]
    var maxLength = 0
    for(var i = 0; i<lengthList.length;i++){
      if(lengthList[i]>maxLength){
        maxLength=lengthList[i]
      }
    }
    console.log(msg)
    for(var i = 0;i<maxLength;i++){
      //type
      if(i<this.data.option1.length&&this.data.option1[i].text===msg.type){
        console.log(msg.type)
        const valueList = this.data.valueList
        valueList[index].value1 = i
        const medicineList = this.data.medicineList
        medicineList[index].type = msg.type
        this.setData({
          valueList:valueList,
          medicineList:medicineList
        })
      }
      //frequency
      if(i<this.data.option3.length&&this.data.option3[i].text===msg.frequency.frequency){
        const medicineList = this.data.medicineList
        //配置frequencyId
        var frequencyList = this.data.frequencyList
        
        var frequencyList1 = new Array(i+1)
        if(frequencyList1.length===1){
          frequencyList1[0] = '12:00:00'
        }else if(frequencyList1.length===2){
          frequencyList1[0] = '12:00:00'
          frequencyList1[1] = '18:00:00'
        }
        else if(frequencyList1.length===3){
          frequencyList1[0] = '8:00:00'
          frequencyList1[1] = '12:00:00'
          frequencyList1[2] = '18:00:00'
        }
        if(index===this.data.index1_copy&&frequencyList.length!=0){
          frequencyList.splice(index,1)
        }
        if(index!=this.data.index1_copy){
          this.setData({
            index1_copy:index
          })
          if(index<frequencyList.length){
            frequencyList.splice(index,1)
          }
        }
        var index1 = this.data.index1
        //神奇？？？只有我和上帝可以看懂！！！
        if(this.data.ret % 2 != 0){
          frequencyList.splice(medicineList.length-1,0,frequencyList1)
          this.setData({
            ret: this.data.ret + 1
          })
        }else{
          frequencyList.splice(index1,0,frequencyList1)
        }
        this.setData({
          // value3:e.detail,
          frequencyList:frequencyList
        })

        medicineList[index].frequencyId = i + 1
        const valueList = this.data.valueList
        valueList[index].value3 = i
        this.setData({
          valueList:valueList,
          medicineList:medicineList
        })
      }
      //mode
      if(i<this.data.option5.length&&this.data.option5[i].text===msg.mode){
        const valueList = this.data.valueList
        valueList[index].value5 = i
        const medicineList = this.data.medicineList
        medicineList[index].mode = msg.mode
        this.setData({
          valueList:valueList,
          medicineList:medicineList
        })
      }
      //unit
      if(i<this.data.option2.length&&this.data.option2[i].text===msg.unit){
        const valueList = this.data.valueList
        const medicineList = this.data.medicineList
        medicineList[index].unit = msg.unit
        valueList[index].value2 = i
        this.setData({
          valueList:valueList,
          medicineList:medicineList
        })
      }
      //dosage
      const medicineList = this.data.medicineList
      medicineList[index].dosage = msg.dosage
      this.setData({
        medicineList:medicineList
      })
    }
  },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    var medicineList = this.data.medicineList
    medicineList[0].elderlyId = options.elderId
    medicineList[0].nurseId = wx.getStorageSync('userid')
    if(options.term=='长期'){
      console.log("长期")
      medicineList[0].endTime = '2099-01-01'
    }
    this.setData({
      elderId:options.elderId,
      medicineList:medicineList,
      term:options.term
    })
    this.query()
    this.queryMedicineList()
  },
  queryMedicineList(){
    wx.request({
      url: 'https://zhixiao.site:8080/client/medication_list/query',
      data:{
        elderlyId:this.data.elderId
      },
      success:(res)=>{
        console.log("haha")
        console.log(res)
        if(Object.keys(res.data.data).length === 0){
          
        }else{
          console.log("haha1")
          var medicineList = res.data.data
          var total_medicineList = []
          for(var i in medicineList){
            if(medicineList[i].length===0){
              continue
            }
            console.log(medicineList[i])
            if(medicineList[i][0].term==='长期'){
              this.setData({
                listId_long:i
              })
            } else if (medicineList[i][0].term==='短期'){
              this.setData({
                listId_short:i
              })
            }
            for(var j in medicineList[i]){
              total_medicineList.push(medicineList[i][j])
            }
          }
          this.setData({
            total_medicineList:total_medicineList
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})